import pymysql
import json
from utils.expand import *


class Database:
    def __init__(self, host, user, password, database):
        self.host = host
        self.user = user
        self.password = password
        self.database = database
        self.connection = None

    def connect(self):
        if not self.connection:
            self.connection = pymysql.connect(
                host=self.host,
                user=self.user,
                password=self.password,
                database=self.database
            )

    def disconnect(self):
        if self.connection:
            self.connection.close()
            self.connection = None

    def execute_query(self, query, params=None):
        self.connect()
        cursor = self.connection.cursor(pymysql.cursors.DictCursor)
        cursor.execute(query, params)
        result = cursor.fetchall()
        cursor.close()
        return result


class DataModel(dict):
    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)

    def __repr__(self):
        return f"DataModel({', '.join(f'{k}={v}' for k, v in self.__dict__.items())})"

    def to_json(self):
        return json.dumps(self.__dict__,ensure_ascii=False)

    def serialize_data_model_list(data_model_list):
        return json.dumps([data_model.__dict__ for data_model in data_model_list],ensure_ascii=False)


@timecost
def get_json_model_data(DataModelList:list) ->str:
    if not DataModelList:
        return "[]"
    data = []
    for data_model in DataModelList:
        dict_single_value = data_model.__dict__
        data.append(dict_single_value)

    json_result = json.dumps(data, ensure_ascii=False)
    return json_result